#include <iostream>
#include <string.h>
using namespace std;

struct teacher {
	int id;
	char name[64];
};
/*
我描述一遍：
1.get_mem传入的是一个结构体的二级指针
2.tp是根据teacher结构体大小开辟的内存，是一个一级指针（指向的是teacher结构体的内存地址，即tp变量的值是个内存地址）
3.*tpp，是对传入的二级指针的一个取值，取出来值得内容是一个teacher结构体的一级指针（tpp指向的是tp的内存地址，*tpp即tp变量的值）
4.*tpp = tp，他们都是两个一级指针，将新开辟tp指针，赋值给teacher的结构体一级指针*tpp
5.最后main方法里面的tp，就有了新开辟，并且填充内容之后的一个指针
*/

// 参数为什么是一个二级指针？
int get_mem(struct teacher **tpp) {
	struct teacher *tp = NULL;
	tp = (struct teacher*) malloc(sizeof(struct teacher));
	if (tp == NULL) {
		return -1;
	}
	tp->id = 100;
	strcpy(tp->name, "li4");
	// 为什么赋值不是**tpp，而是*tpp
	*tpp = tp;
	return 0;
}

int get_mem2(struct teacher* &tp) {
	tp = (struct teacher*) malloc(sizeof(struct teacher));
	if (tp == NULL) {
		return -1;
	}
	tp->id = 100;
	strcpy(tp->name, "wang5");
	return 0;
}

void free_teacher(struct teacher **tpp) {
	if (tpp == NULL) {
		return;
	}
	struct teacher *tp = *tpp;
	if (tp != NULL) {
		free(tp);
		// 为什么不是**tpp = NULL?
		*tpp = NULL;
	}
}

void free_teacher2(struct teacher* &tp) {
	if (tp != NULL) {
		free(tp);
		tp = NULL;
	}
}


int get_mem3(struct teacher *tpp) {
	struct teacher *tp = NULL;
	tp = (struct teacher*) malloc(sizeof(struct teacher));
	if (tp == NULL) {
		return -1;
	}
	tp->id = 100;
	strcpy(tp->name, "zhao6");
	tpp = tp;
	return 0;
}

int main(int argc, char *argv[]) {

	struct teacher *tp = NULL;
	get_mem(&tp);
	cout << "id=" << tp->id << ", name=" << tp->name << endl;
	free_teacher(&tp);

	cout << "-----" << endl;
	get_mem2(tp);
	cout << "id=" << tp->id << ", name=" << tp->name << endl;
	free_teacher2(tp);

//	cout << "-----" << endl;
//	get_mem3(tp);
//	cout << "id=" << tp->id << ", name=" << tp->name << endl;
//	free_teacher2(tp);

	return 0;
}





